package main

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/opentracing/opentracing-go"
	"github.com/uber/jaeger-client-go"
	jaegercfg "github.com/uber/jaeger-client-go/config"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"net/http"
	"oldpackagetest/gin_jaeger_test/gin/otgrpc"
	"oldpackagetest/gin_jaeger_test/gin/proto"
)

// 拦截器
func Trace() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//jaeger配置
		cfg := jaegercfg.Configuration{
			Sampler: &jaegercfg.SamplerConfig{
				Type:  jaeger.SamplerTypeConst,
				Param: 1, //全部采样
			},
			Reporter: &jaegercfg.ReporterConfig{
				//当span发送到服务器时要不要打日志
				LogSpans:           true,
				LocalAgentHostPort: "192.168.10.130:6831",
			},
			ServiceName: "gin-grpc",
		}
		//创建jaeger
		tracer, closer, err := cfg.NewTracer(jaegercfg.Logger(jaeger.StdLogger))
		if err != nil {
			panic(err)
		}
		defer closer.Close()
		//最开始的span，以url开始
		startSpan := tracer.StartSpan(ctx.Request.URL.Path)
		defer startSpan.Finish()
		ctx.Set("tracer", tracer)
		ctx.Set("parentSpan", startSpan)
		ctx.Next()
	}
}

func main() {
	router := gin.Default()
	router.Use(Trace())
	router.GET("/jaeger", func(ctx *gin.Context) {
		conn, err := grpc.Dial("127.0.0.1:50052", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer())))
		if err != nil {
			panic(err)
		}
		defer conn.Close()
		cc := proto.NewGreeterClient(conn)
		//将gin.context放到context里
		r, err := cc.SayHello(context.WithValue(context.Background(), "ginContext", ctx), &proto.HelloRequest{Name: "bobby"})
		ctx.JSON(http.StatusOK, gin.H{
			"msg": r.Message,
		})
	})
	_ = router.Run(":8083")
}
